<script setup>
import {ref} from 'vue'
import {ElMessage} from 'element-plus'

import {getCategoryApi} from '@/api/@/api/category'

const categoryList = ref([])
// 从接口获取数据
getCategoryApi().then(res => {
  categoryList.value = res.data
})

const ruleForm = ref({name: '', sex: '', event_date: '', category: '', remark: '',});
const rules = ref({
  name: [{required: true, message: '请输入Name', trigger: 'blur'}],
  sex: [{required: true, message: '请选择Sex', trigger: 'change'}],
  event_date: [{required: true, message: '请选择Event Date', trigger: 'change'}],
  category: [{required: true, message: '请选择Category', trigger: 'change'}],
  remark: [{required: true, message: '请输入Remark', trigger: 'blur'}],
});

import {doFormApi} from '@/api/form';

const ruleFormRef = ref(null);
const onSubmit = () => {
  ruleForm.value.validate((valid) => {
    if (valid) {
      doFormApi(ruleForm.value).then(res => {
        if (res.code === 200) {
          ElMessage.success(res.msg);
          ruleFormRef.value.resetFields();
          emits('reload');
        } else {
          ElMessage.error(res.msg);
        }
      })
    }
  })
}


const emits = defineEmits(['reload'])

const dialogVisible = ref(false)
const openDialog = () => {
  dialogVisible.value = true;

  getCategoryApi();

}
const closeDialog = () => {
  dialogVisible.value = false;
  // 重置表单
  ruleFormRef.value.resetFields();
}

defineExpose({
  openDialog,
  closeDialog
});

</script>

<template>
  <el-dialog title="Dialog Title" v-model="dialogVisible" width="30%">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="80px" label-position="right">

      <el-form-item label="Name" prop="name">
        <el-input v-model="ruleForm.name"></el-input>
      </el-form-item>

      <el-form-item label="Sex" prop="sex">
        <el-radio-group v-model="ruleForm.sex">
          <el-radio v-for="item in [{'id': 0, 'title': 'Female'}, {'id': 1, 'title': 'Male'}]" :key="item.value"
                    :label="item.value">{ item.label }
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="Event Date" prop="event_date">
        <el-date-picker v-model="ruleForm.event_date" type="date" placeholder="选择日期"></el-date-picker>
      </el-form-item>

      <el-form-item label="Category" prop="category">
        <el-select v-model="ruleForm.category">
          <el-option v-for="item in categoryList" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="Remark" prop="remark">
        <el-input type="textarea" v-model="ruleForm.remark"></el-input>
      </el-form-item>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="onSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>
        